#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <unistd.h>

int sockfd;
void print(int signal)
{
	close(sockfd);
	printf("server is closing...\n");
	exit(0);	
}

int main()
{
	signal(SIGINT,print);
	sockfd = socket(PF_INET , SOCK_STREAM , 0);
	struct sockaddr_in addr;
	addr.sin_family = PF_INET;
	addr.sin_port = htons(2222);
	addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	//解决重启时地址被占用问题
	int reuseaddr = 1;
	setsockopt(sockfd , SOL_SOCKET, SO_REUSEADDR,&reuseaddr,sizeof(reuseaddr));
	int res = bind(sockfd , (struct sockaddr *)&addr , sizeof(addr));
	if(res == -1)
		perror("bind"),exit(-1);
	printf("bind ...\n");
	listen(sockfd , 2);
	printf("listen ...\n");
	
	struct sockaddr_in  clientaddr ;
	int len = sizeof(clientaddr);
	char buf[100] ;	
	while(1)
	{
		memset(&clientaddr , 0x00 , sizeof(clientaddr));
		memset(buf , 0x00 , sizeof(buf) );
		int newsock = accept(sockfd , (struct sockaddr *)&clientaddr , &len);
		int pid = fork();
		if(pid == 0)
		{
			while(1)
			{			
				read(newsock , buf , sizeof(buf));
				printf("receive : %s\n",buf);
				if(strcmp(buf,"bye") == 0)
					break;
				//write(sockfd , buf , sizeof(buf));
			}		
			close(newsock);
			exit(0);
		}
		
	}
	close(sockfd);
	return 0;
}





